﻿using System.Collections.Generic;

public class DataWatcher<T>
{
    public delegate void OnValueChangeEvent(T newValue, T oldValue);

    private T _value;
    private List<OnValueChangeEvent> _listener = null;
    public T Value {
        get { return _value; }
        set {
            if (!value.Equals(_value)) {
                distrubute(value, _value);
                _value = value;
            }
        }
    }

    public DataWatcher(T defaultValue = default(T))
    {
        _listener = new List<OnValueChangeEvent>();
        _value = defaultValue;
    }

    public void AddObserver(OnValueChangeEvent inEvent)
    {
        if (_listener.Contains(inEvent)) {
            UnityEngine.Debug.LogWarning("DataWatcher: listener is exists, dont't repeated addition.");
        } else {
            _listener.Add(inEvent);
        }
    }

    public void RemoveObserver(OnValueChangeEvent inEvent)
    {
        if (_listener.Contains(inEvent)) {
            _listener.Remove(inEvent);
        } else {
            UnityEngine.Debug.LogError("DataWatcher: listener isn't exists, can't remove...");
        }
    }

    private void distrubute(T newValue, T oldValue)
    {
        for (int i = 0; i < _listener.Count; i++) {
            _listener[i](newValue, oldValue);
        }
    }

}
